package thread;

import java.util.*;

/**
 * 集合实例, 线程安全
 * ArrayList, LinkedList, HashSet
 * 这些都是并发不安全的
 */
public class SyncAPIDemo2 {
    public static void main(String[] args) {
        //List<Integer> c=new ArrayList<>();
        //List<Integer> c=new LinkedList<>();
        //Set<Integer> c=new HashSet<>();

        //解决方案:将集合转换成并发安全的集合 Collections.synchronizedList(c);
        //List<Integer> c=Collections.synchronizedList(new ArrayList<>());
        //List<Integer> c=Collections.synchronizedList(new LinkedList<>());
        //Map<Integer,Integer> c=Collections.synchronizedMap(new HashMap<>());
        Set<Integer> c=Collections.synchronizedSet(new HashSet<>());

        Thread t1=new Thread(){
            public void run(){
                for (int i=0;i<1000;i++){
                    c.add(i);
                }
            }
        };
        Thread t2=new Thread(){
            public void run(){
                for (int i=1000;i<2000;i++){
                    c.add(i);
                }
            }
        };
        t1.start();
        t2.start();

        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {

        }

        System.out.println(c.size());


    }
}
